using MeasureAbstract.IMotionDevice;
using System;
using System.Collections.ObjectModel;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;
using System.IO.Ports;
using SixLabors.ImageSharp.Memory;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Media;
using System.Windows;
using System.Threading.Tasks;
using System.IO;
using CommunityToolkit.Mvvm.ComponentModel;
using System.Windows.Controls;

namespace 长屏_ARM_STM32F429控制板
{
    public partial class Turntable : IMotionDevice
    {
        

        #region
        public Turntable()
        {
            Config = new MotionDeviceConfig();
            //设置支持的通信方式
            Config.CommunicationList = new ObservableCollection<CommunicationMode>()
            {
                new CommunicationMode() {Name="TCP",Selected=true,Support=true},
                new CommunicationMode() {Name="UDP",Selected=false,Support=true},
                new CommunicationMode() {Name="UART",Selected=false,Support=true},
            };
            //设置默认通信参数
            Config.LocalIP = "10.0.0.20";
            Config.LocalPort = "8080";
            Config.DestIP = "10.0.0.100";
            Config.DestPort = "8080";
            Config.PortName = "COM1";
            Config.BandRate = "115200";

            //设置轴
            if (Config.Axes == null)
            {
                Config.Axes = new System.Collections.ObjectModel.ObservableCollection<Axis>();
            }
            Config.Axes.Clear();
            Config.Axes.Add(new Axis() { AxisID = 1, AxisName = "方位轴", Accuracy = 0.01, SupportPulseOut = true });
            Config.Axes.Add(new Axis() { AxisID = 2, AxisName = "俯仰轴", Accuracy = 0.01, SupportPulseOut = true });


            AnalyzeData_Func = AnalyzeData;
            Timer = new System.Timers.Timer();
            Timer.Interval = 3000;
            Timer.Elapsed += Timer_Elapsed;
        }

        private int AnalyzeData(byte[] data)
        {
            //解析数据
            if (data.Length < 6) return -1;
            if (data.Length != data[2])
            {
                return -1;
            }
            switch(data[3])
            {
                case 2:
                    switch(data[4])
                    {
                        case 1:
                            int j = 0;
                            for (int i = 0; i < data[5]; i++)
                            {
                                foreach (var temp in Config.Axes)
                                {
                                    if (temp.AxisID == data[6 + j])
                                    {
                                        temp.CurrentPosition = BitConverter.ToSingle(data, 7 + j);
                                        j += 5;
                                        break;
                                    }
                                }
                            }
                            break;
                    }
                    break;
                case 253:
                    HeartBeatFlag = true;
                    break;
                default: break;
            }
            return 0;
        }

        public override string Name => "转台";

        public override string Vender => "长屏";


        public override string Model => "ARM_STM32F429";

        public override string Description => "长屏自主开发的控制卡";


        public override MotionDeviceConfig? Config { get; set; }



        #endregion


        System.Timers.Timer? Timer;
        private void Timer_Elapsed(object? sender, System.Timers.ElapsedEventArgs e)
        {
            //处理心跳


            if(HeartBeatEnable)
            {
                HeartBeat(ref HeartBeatFlag, 2000);
            }

        }


        #region 数据收发
        TcpClient? TCPClient;
        UdpClient? UdpClient;
        IPEndPoint RemoteEndPoint;
        SerialPort? SerialPort;
        Thread Thread;
        private NetworkStream stream;
        public object HeartBeatFlag = false;
        [ObservableProperty]
        private bool heartBeatEnable = true;
        public Func<byte[], int> AnalyzeData_Func;

        public override void Connect()
        {
            string SelectedCommunication = "";
            foreach (var temp in Config.CommunicationList)
            {
                if (temp.Selected)
                {
                    SelectedCommunication = temp.Name;
                }
            }
            // 创建一个CancellationTokenSource，用于取消连接操作
            CancellationTokenSource CancellationTokenSource = new CancellationTokenSource();
            
            if (!ConnectState)
            {
                switch (SelectedCommunication.ToUpper())
                {
                    case "TCP":
                        //TCPClient = new TcpClient();
                        //Task ConnectTask = TCPClient.ConnectAsync(Config.DestIP, int.Parse(Config.DestPort), CancellationTokenSource.Token).AsTask();

                        //// 设置连接超时时间为5秒
                        //Task TimeoutTask = Task.Delay(1000);

                        //// 使用Task.WhenAny等待连接完成或超时
                        //Task CompletedTask = await Task.WhenAny(ConnectTask, TimeoutTask);

                        //// 如果连接完成任务是连接任务，则连接成功
                        //if (CompletedTask == ConnectTask)
                        //{
                        //    stream = TCPClient.GetStream();
                        //    ConnectState = true;
                        //    //开启接收线程
                        //    while (!TCPClient.Connected) ;
                        //    Thread = new Thread(TCPReceive);
                        //    Thread.Start();
                        //    while (Thread.ThreadState != ThreadState.Running)
                        //    {

                        //    }

                        //}
                        //else
                        //{
                        //    CancellationTokenSource.Cancel();
                        //    TCPClient.Close();
                        //    ConnectState = false;
                        //    throw new Exception($"{Vender}_{Model}TCP连接超时!");
                        //}


                        TCPClient = new TcpClient();
                        IAsyncResult ConnResult =  TCPClient.BeginConnect(Config.DestIP, int.Parse(Config.DestPort),null,null);

                        ConnResult.AsyncWaitHandle.WaitOne(1000,true);

                        if (!ConnResult.IsCompleted)
                        {
                            TCPClient.Close();
                            ConnectState = false;
                            throw new Exception($"{Vender}_{Model}TCP连接超时!");
                        }
                        else
                        {
                            stream = TCPClient.GetStream();
                            ConnectState = true;
                            //开启接收线程
                            Thread = new Thread(TCPReceive);
                            Thread.Start();
                            while (Thread.ThreadState != ThreadState.Running)
                            {

                            }
                        }




                        //TCPClient = new TcpClient();
                        //TCPClient.Connect(Config.DestIP, int.Parse(Config.DestPort));
                        //stream = TCPClient.GetStream();
                        //ConnectState = true;
                        ////开启接收线程
                        //while (!TCPClient.Connected) ;
                        //Thread = new Thread(TCPReceive);
                        //Thread.Start();
                        //while (Thread.ThreadState != ThreadState.Running)
                        //{

                        //}
                        break;
                    case "UDP":
                        UdpClient = new UdpClient();
                        //UdpClient.Client.Bind(new IPEndPoint(IPAddress.Parse(Config.LocalIP), int.Parse(Config.LocalPort)));
                        RemoteEndPoint = new IPEndPoint(IPAddress.Parse(Config.DestIP), int.Parse(Config.DestPort));
                        UdpClient.Connect(RemoteEndPoint);
                        ConnectState = true;
                        //开启接收线程
                        Thread = new Thread(UDPReceive);
                        Thread.Start();
                        while (Thread.ThreadState != ThreadState.Running)
                        {

                        }
                        break;
                    case "UART":
                        SerialPort = new SerialPort();
                        SerialPort.PortName = Config.PortName;
                        SerialPort.BaudRate = int.Parse(Config.BandRate);
                        SerialPort.Open();
                        ConnectState = true;
                        //开启接收线程
                        Thread = new Thread(UARTReceive);
                        Thread.Start();
                        while (Thread.ThreadState != ThreadState.Running)
                        {

                        }
                        break;
                    case "GPIB":
                        throw new NotImplementedException();
                    case "USB":
                        throw new NotImplementedException();
                    default:
                        throw new NotImplementedException();
                }
                Timer.Start();
            }
            else
            {
                //已经处于连接状态，不进行操作
            }
        }
        private void UARTReceive(object? obj)
        {
            while (true)
            {
                try
                {
                    byte[] receivedData = new byte[4];
                    if (!SerialPort.IsOpen)
                    {
                        Application.Current.Dispatcher.BeginInvoke(() => { throw new Exception($"{Vender}_{Model}串口连接断开!"); });
                        break;
                    }
                    if (SerialPort.BytesToRead > 0)
                    {
                        SerialPort.Read(receivedData, 0, SerialPort.BytesToRead);
                        //检测是否为一个完整的数据，是则进行分析，否则继续接收或丢弃


                        try
                        {
                            AnalyzeData_Func?.Invoke(receivedData);
                        }
                        catch
                        {
                            //数据错误不处理
                        }
                    }


                }
                catch (Exception e)
                {

                    DisConnect();
                    //Application.Current.Dispatcher.BeginInvoke(() => { throw new Exception($"{Vender}_{Model}串口连接断开,{e.Message}"); });
                    Application.Current.Dispatcher.BeginInvoke(() => { throw new Exception($"{Vender}_{Model}串口连接断开!"); });
                    break;
                }
            }
        }

        private void UDPReceive(object? obj)
        {
            while (true)
            {
                try
                {
                    byte[] receivedData = UdpClient.Receive(ref RemoteEndPoint);
                    try
                    {
                        AnalyzeData_Func?.Invoke(receivedData);
                    }
                    catch
                    {
                        //数据错误不处理
                    }
                }
                catch (Exception e)
                {

                    DisConnect();
                    //Application.Current.Dispatcher.BeginInvoke(() => { throw new Exception($"{Vender}_{Model}UDP连接断开,{e.Message}"); });
                    Application.Current.Dispatcher.BeginInvoke(() => { throw new Exception($"{Vender}_{Model}UDP连接断开!"); });
                    break;
                }
            }
        }

        private void TCPReceive(object? obj)
        {
            while (true)
            {
                try
                {
                    byte[] buffer = new byte[1024];
                    if (stream.CanRead)
                    {
                        int bytesRead = stream.Read(buffer, 0, buffer.Length);
                        Array.Resize(ref buffer, bytesRead);
                        try
                        {
                            AnalyzeData_Func?.Invoke(buffer);
                        }
                        catch
                        {
                            //数据错误不处理
                        }
                    }
                }
                catch (IOException e)
                {

                    DisConnect();
                    //Application.Current.Dispatcher.BeginInvoke(() => { throw new Exception($"{Vender}_{Model}TCP连接断开,{e.Message}"); });
                    Application.Current.Dispatcher.BeginInvoke(() => { throw new Exception($"{Vender}_{Model}TCP连接断开!"); });
                    break;
                }
            }
        }

        public override void DisConnect()
        {
            string SelectedCommunication = "";
            foreach (var temp in Config.CommunicationList)
            {
                if (temp.Selected)
                {
                    SelectedCommunication = temp.Name;
                }
            }
            if (ConnectState)
            {
                switch (SelectedCommunication.ToUpper())
                {
                    case "TCP":
                        stream.Close();
                        TCPClient?.Close();
                        ConnectState = false;
                        break;
                    case "UDP":
                        UdpClient?.Close();
                        ConnectState = false;
                        break;
                    case "UART":
                        SerialPort?.Close();
                        ConnectState = false;
                        break;
                    case "GPIB":
                        throw new NotImplementedException();
                    case "USB":
                        throw new NotImplementedException();
                    default:
                        throw new NotImplementedException();
                }
                Timer.Stop();
            }
            else
            {
                //已经处于关闭状态,不进行操作
            }
        }

        public virtual int SendData(byte[] Data)
        {
            string SelectedCommunication = "";
            foreach (var temp in Config.CommunicationList)
            {
                if (temp.Selected)
                {
                    SelectedCommunication = temp.Name;
                }
            }
            if (ConnectState)
            {
                switch (SelectedCommunication.ToUpper())
                {
                    case "TCP":
                        stream.Write(Data, 0, Data.Length);
                        break;
                    case "UDP":
                        //UdpClient?.Send(Data, Data.Length, RemoteEndPoint);
                        UdpClient?.Send(Data, Data.Length);
                        break;
                    case "UART":
                        SerialPort?.Write(Data, 0, Data.Length);
                        break;
                    case "GPIB":
                        throw new NotImplementedException();
                    case "USB":
                        throw new NotImplementedException();
                    default:
                        throw new NotImplementedException();
                }
            }
            else
            {
                throw new Exception($"{Vender}_{Model}未连接!");
            }
            return 0;
        }

        public override void HeartBeat(ref object ResponseFlag, int MaxResponseTime_ms)
        {
            ResponseFlag = false;
            byte[] Command = new byte[1];
            BuildCommand(ref Command, 253, 255, null);
            SendData(Command);
            DateTime s = DateTime.Now;
            while (true)
            {
                if ((bool)ResponseFlag == true)
                {
                    //收到应答
                    return;
                }
                if ((DateTime.Now - s).TotalMilliseconds > MaxResponseTime_ms)
                {
                    //超时了
                    DisConnect();
                    Application.Current.Dispatcher.BeginInvoke(() => { throw new Exception($"{Vender}_{Model}心跳检测超时,已断开连接,请检查!"); });
                    return;
                }
            }
        }
        #endregion


        public void BuildCommand(ref byte[] Command, int Cmd_M, int Cmd_A, List<DataSegment>? Data = null)
        {
            int Length = 0;
            byte Sum = 0;
            byte[] cmd = new byte[1];
            if (Data == null)
            {
                Length = 6;
            }
            else
            {
                foreach (var temp in Data)
                {
                    switch (temp.Type)
                    {
                        case "byte":
                            Length += 1;
                            cmd = cmd.Concat(new byte[1] { byte.Parse(temp.Value) }).ToArray();
                            break;
                        case "short":
                            Length += 2;
                            cmd = cmd.Concat(BitConverter.GetBytes(short.Parse(temp.Value))).ToArray();
                            break;
                        case "int":
                            Length += 4;
                            cmd = cmd.Concat(BitConverter.GetBytes(int.Parse(temp.Value))).ToArray();
                            break;
                        case "float":
                            Length += 4;
                            cmd = cmd.Concat(BitConverter.GetBytes(float.Parse(temp.Value))).ToArray();
                            break;
                        case "double":
                            Length += 8;
                            cmd = cmd.Concat(BitConverter.GetBytes(double.Parse(temp.Value))).ToArray();
                            break;
                        case "string":
                            Length += System.Text.Encoding.Default.GetBytes(temp.Value).Length;
                            cmd = cmd.Concat(System.Text.Encoding.Default.GetBytes(temp.Value)).ToArray();
                            break;
                        default:
                            throw new Exception("不支持的数据类型!");
                    }
                }
                Length += 6;
            }
            Array.Resize(ref Command, Length);
            Array.Clear(Command);
            Command[0] = (byte)'c';
            Command[1] = (byte)'p';
            Command[2] = (byte)Length;
            Command[3] = (byte)Cmd_M;
            Command[4] = (byte)Cmd_A;
            if (Data != null)
            {
                for (int i = 0; i < Length - 6; i++)
                {
                    Command[i + 5] = cmd[1 + i];
                }
            }
            for (int i = 0; i < Length - 1; i++)
            {
                Sum += Command[i];
            }
            Command[Length - 1] = (byte)Sum;
        }

        public override int Enable(int AxisID)
        {
            byte[] Command = new byte[1];
            var dataSegments = new List<DataSegment>();
            dataSegments.Add(new DataSegment() { Value = AxisID.ToString(), Type = "byte" });
            BuildCommand(ref Command, 0, 1, dataSegments);
            SendData(Command);
            return 0;
        }
        public override int Disable(int AxisID)
        {
            byte[] Command = new byte[1];
            var dataSegments = new List<DataSegment>();
            dataSegments.Add(new DataSegment() { Value = AxisID.ToString(), Type = "byte" });
            BuildCommand(ref Command, 0, 0, dataSegments);
            SendData(Command);
            return 0;

        }
        public override int Run(int AxisID, double Position, double Speed, double Acc, double Dcc, bool AbsoluteMovement = true)
        {
            byte[] Command = new byte[1];
            List<DataSegment> dataSegments = new List<DataSegment>();
            dataSegments.Add(new DataSegment() { Value = AxisID.ToString(), Type = "byte" });
            dataSegments.Add(new DataSegment() { Value = Position.ToString(), Type = "float" });
            dataSegments.Add(new DataSegment() { Value = Speed.ToString(), Type = "float" });
            if (AbsoluteMovement)
            {
                dataSegments.Add(new DataSegment() { Value = "1", Type = "byte" });
            }
            else
            {
                dataSegments.Add(new DataSegment() { Value = "0", Type = "byte" });
            }

            BuildCommand(ref Command, 1, 1, dataSegments);
            SendData(Command);
            return 0;
        }

        public override int Stop(int AxisID)
        {
            byte[] Command = new byte[1];
            var dataSegments = new List<DataSegment>();
            dataSegments.Add(new DataSegment() { Value = AxisID.ToString(), Type = "byte" });
            BuildCommand(ref Command, 1, 0, dataSegments);
            SendData(Command);
            return 0;
        }

        public override void ReSet()
        {
            throw new NotImplementedException();
        }

        public override bool ReachedState(int AxisID)
        {
            throw new NotImplementedException();
        }

        public override int TriggerOpen(int AxisID, double StartPosition, double EndPosition, double Interval, int PuslseWidth_us)
        {
            byte[] Command = new byte[1];
            var dataSegments = new List<DataSegment>();
            dataSegments.Add(new DataSegment() { Value = AxisID.ToString(), Type = "byte" });
            dataSegments.Add(new DataSegment() { Value = StartPosition.ToString(), Type = "float" });
            BuildCommand(ref Command, 2, 2, dataSegments);
            SendData(Command);
            Thread.Sleep(10);
            dataSegments = new List<DataSegment>();
            dataSegments.Add(new DataSegment() { Value = AxisID.ToString(), Type = "byte" });
            dataSegments.Add(new DataSegment() { Value = EndPosition.ToString(), Type = "float" });
            BuildCommand(ref Command, 2, 3, dataSegments);
            SendData(Command);
            Thread.Sleep(10);
            dataSegments = new List<DataSegment>();
            dataSegments.Add(new DataSegment() { Value = AxisID.ToString(), Type = "byte" });
            dataSegments.Add(new DataSegment() { Value = Interval.ToString(), Type = "float" });
            BuildCommand(ref Command, 2, 4, dataSegments);
            SendData(Command);
            Thread.Sleep(10);
            dataSegments = new List<DataSegment>();
            dataSegments.Add(new DataSegment() { Value = AxisID.ToString(), Type = "byte" });
            dataSegments.Add(new DataSegment() { Value = PuslseWidth_us.ToString(), Type = "int" });
            BuildCommand(ref Command, 2, 5, dataSegments);
            SendData(Command);
            Thread.Sleep(10);
            dataSegments = new List<DataSegment>();
            dataSegments.Add(new DataSegment() { Value = AxisID.ToString(), Type = "byte" });
            BuildCommand(ref Command, 2, 1, dataSegments);
            SendData(Command);
            return 0;
        }

        public override int TriggerClose(int AxisID)
        {
            byte[] Command = new byte[1];
            var dataSegments = new List<DataSegment>();
            dataSegments.Add(new DataSegment() { Value = AxisID.ToString(), Type = "byte" });
            BuildCommand(ref Command, 2, 0, dataSegments);
            SendData(Command);
            return 0;
        }

        public override int TriggerOne(int AxisID)
        {
            byte[] Command = new byte[1];
            var dataSegments = new List<DataSegment>();
            dataSegments.Add(new DataSegment() { Value = AxisID.ToString(), Type = "byte" });
            BuildCommand(ref Command, 2, 6, dataSegments);
            SendData(Command);
            return 0;
        }
    }
    public class DataSegment
    {
        public string Value { get; set; } = "";
        public string Type { get; set; } = "";
    }



    //public partial class Turntable2 : IMotionDevice
    //{
    //    #region
    //    public Turntable2()
    //    {
    //        Config = new MotionDeviceConfig();
    //        //设置支持的通信方式
    //        Config.CommunicationList = new ObservableCollection<CommunicationMode>()
    //        {
    //            new CommunicationMode() {Name="TCP",Selected=true,Support=true},
    //            new CommunicationMode() {Name="UDP",Selected=false,Support=true},
    //            new CommunicationMode() {Name="UART",Selected=false,Support=true},
    //        };
    //        //设置默认通信参数
    //        Config.LocalIP = "10.0.0.20";
    //        Config.LocalPort = "8080";
    //        Config.DestIP = "10.0.0.100";
    //        Config.DestPort = "8080";
    //        Config.PortName = "COM1";
    //        Config.BandRate = "115200";

    //        //设置轴
    //        if (Config.Axes == null)
    //        {
    //            Config.Axes = new System.Collections.ObjectModel.ObservableCollection<Axis>();
    //        }
    //        Config.Axes.Clear();
    //        Config.Axes.Add(new Axis() { AxisID = 1, AxisName = "方位轴", Accuracy = 0.01, SupportPulseOut = true });
    //        Config.Axes.Add(new Axis() { AxisID = 2, AxisName = "俯仰轴", Accuracy = 0.01, SupportPulseOut = true });


    //    }
    //    public override string Name => "转台";

    //    public override string Vender => "长屏";


    //    public override string Model => "ARM_STM32F429";

    //    public override string Description => "长屏自主开发的控制卡";


    //    public override MotionDeviceConfig? Config { get; set; }



    //    #endregion

    //    SerialPort? SerialPort;
    //    Socket? ClientSocket;
    //    Thread? ReceiveThread;
    //    EndPoint? EndPoint;
    //    System.Timers.Timer? Timer;
    //    private bool StopThreadFlag = false;

    //    private readonly ManualResetEvent TimeoutObject = new ManualResetEvent(false);
    //    public Func<byte[], int>? Send_Func { get; set; }


    //    public void Connect(IPEndPoint remoteEndPoint, int timeoutMSec)
    //    {
    //        TimeoutObject.Reset();
    //        ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    //        ClientSocket.BeginConnect(remoteEndPoint, CallBackMethod, ClientSocket);
    //        //阻塞当前线程           
    //        if (TimeoutObject.WaitOne(timeoutMSec, false))
    //        {

    //        }
    //        else
    //        {
    //            throw new Exception($"TCP连接{Vender}{Model}{Name}超时");
    //        }
    //    }
    //    private void CallBackMethod(IAsyncResult asyncresult)
    //    {
    //        //使阻塞的线程继续        
    //        TimeoutObject.Set();
    //    }
    //    public int SendData(byte[] Data)
    //    {
    //        if (!ConnectState)
    //        {
    //            throw new Exception("转台未连接!");
    //        }
    //        string SelectedCommunication = "";
    //        foreach (var temp in Config.CommunicationList)
    //        {
    //            if (temp.Selected)
    //            {
    //                SelectedCommunication = temp.Name;
    //            }
    //        }
    //        switch (SelectedCommunication.ToUpper())
    //        {
    //            case "TCP":
    //                ClientSocket?.Send(Data);
    //                break;
    //            case "UDP":
    //                ClientSocket?.SendTo(Data, EndPoint!);
    //                break;
    //            case "UART":
    //                SerialPort?.Write(Data, 0, Data.Length);
    //                break;
    //            default:
    //                throw new Exception("不支持的通信方式");
    //        }
    //        return 0;
    //    }
    //    private void TCPRecive(object? obj)
    //    {
    //        byte[] data = new byte[128];
    //        while (!StopThreadFlag)
    //        {
    //            try
    //            {
    //                Array.Resize(ref data, 128);
    //                Array.Clear(data, 0, data.Length);
    //                if (!ClientSocket.Connected) { ClientSocket.Disconnect(true); TerminateReceive(); continue; }
    //                int Length = (int)(ClientSocket?.Receive(data)!);
    //                Array.Resize(ref data, Length);
    //                //解析数据
    //                if (Length <= 6) continue;
    //                if (Length != data[2])
    //                {
    //                    continue;
    //                }

    //                int j = 0;
    //                for (int i = 0; i < data[5]; i++)
    //                {
    //                    foreach (var temp in Config.Axes)
    //                    {
    //                        if (temp.AxisID == data[6 + j])
    //                        {
    //                            temp.CurrentPosition = BitConverter.ToSingle(data, 7 + j);
    //                            j += 5;
    //                            break;
    //                        }
    //                    }
    //                }
    //            }
    //            catch (Exception ex)
    //            {
    //                Application.Current.Dispatcher.BeginInvoke(() => { throw ex; });

    //                return;
    //            }
    //        }
    //    }
    //    private void UDPRecive(object? obj)
    //    {
    //        byte[] data = new byte[128];
    //        EndPoint point = new IPEndPoint(IPAddress.Any, 0);//用来保存发送方的ip和端口号
    //        while (!StopThreadFlag)
    //        {
    //            try
    //            {
    //                Array.Resize(ref data, 128);
    //                Array.Clear(data, 0, data.Length);
    //                int Length = (int)(ClientSocket?.ReceiveFrom(data, ref point)!);
    //                Array.Resize(ref data, Length);
    //                //解析数据
    //                int j = 0;
    //                for (int i = 0; i < data[5]; i++)
    //                {
    //                    foreach (var temp in Config.Axes)
    //                    {
    //                        if (temp.AxisID == data[6 + j])
    //                        {
    //                            temp.CurrentPosition = BitConverter.ToSingle(data, 7 + j);
    //                            break;
    //                        }
    //                    }
    //                    j += 5;
    //                }
    //            }
    //            catch
    //            {
    //                return;
    //            }
    //        }
    //    }
    //    private void Timer_Elapsed(object? sender, System.Timers.ElapsedEventArgs e)
    //    {
    //        //询问位置信息
    //        byte[] cmd = new byte[3];
    //        cmd[0] = 0xFF;
    //        cmd[1] = 0x01;
    //        cmd[2] = 0xFE;
    //        SendData(cmd);
    //    }
    //    string? strData;

    //    private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    //    {
    //        StringBuilder sb = new StringBuilder();
    //        if (SerialPort == null) return;
    //        int len = this.SerialPort.BytesToRead;
    //        byte[] buffer = new byte[len];
    //        SerialPort.Read(buffer, 0, len);
    //        strData = BitConverter.ToString(buffer, 0, len);
    //        //this.Invoke(new Action(() => { textBox4.Text = buffer.Length.ToString(); }));
    //        if (buffer.Length == 9 && buffer[1] == 3)//读取位置数据指令反馈
    //        {
    //            string str_Data = buffer[5].ToString("X2") + buffer[6].ToString("X2") + buffer[3].ToString("X2") + buffer[4].ToString("X2");
    //            if (buffer[5] > 240)//F0表示负数，补码转原码处理
    //            {
    //                Int32 iTmp = Convert.ToInt32(str_Data, 16) - 1;//得到反码数值
    //                Int32 iTmp2 = ~iTmp;
    //                string ystr = Convert.ToString(iTmp2, 2).PadLeft(32, '0');
    //                if (buffer[0] == 1)
    //                {
    //                    Config.Axes![0].CurrentPosition = (0 - Convert.ToInt32(ystr, 2));
    //                }
    //                else if (buffer[0] == 2)
    //                {
    //                    Config.Axes![1].CurrentPosition = (0 - Convert.ToInt32(ystr, 2));
    //                }
    //                else if (buffer[0] == 3)
    //                {
    //                    Config.Axes![2].CurrentPosition = (0 - Convert.ToInt32(ystr, 2));
    //                }
    //            }
    //            else//正数直接处理
    //            {
    //                Int32 iTmp = Convert.ToInt32(str_Data, 16);
    //                string ystr = Convert.ToString(iTmp, 2).PadLeft(32, '0');
    //                if (buffer[0] == 1)
    //                {
    //                    Config.Axes![0].CurrentPosition = Convert.ToInt32(ystr, 2);
    //                }
    //                else if (buffer[0] == 2)
    //                {
    //                    Config.Axes![1].CurrentPosition = Convert.ToInt32(ystr, 2);
    //                }
    //                else if (buffer[0] == 3)
    //                {
    //                    Config.Axes![2].CurrentPosition = Convert.ToInt32(ystr, 2);
    //                }
    //            }

    //        }
    //    }
    //    public int StartReceive()
    //    {
    //        string SelectedCommunication = "";
    //        foreach (var temp in Config.CommunicationList)
    //        {
    //            if (temp.Selected)
    //            {
    //                SelectedCommunication = temp.Name;
    //            }
    //        }
    //        switch (SelectedCommunication.ToUpper())
    //        {
    //            case "TCP":
    //                ReceiveThread = new Thread(TCPRecive);
    //                ReceiveThread.Start();

    //                break;
    //            case "UDP":
    //                ReceiveThread = new Thread(UDPRecive);
    //                ReceiveThread.Start();
    //                Timer = new System.Timers.Timer();
    //                Timer.Elapsed += Timer_Elapsed;
    //                Timer.Interval = 500;
    //                Timer.Enabled = true;
    //                Timer.Start();
    //                break;
    //            case "UART":
    //                if (SerialPort != null)
    //                {
    //                    SerialPort.DataReceived += SerialPort_DataReceived; //用接收事件接收数据,也可开启线程接收
    //                }
    //                Timer = new System.Timers.Timer();
    //                Timer.Elapsed += Timer_Elapsed;
    //                Timer.Interval = 500;
    //                Timer.Enabled = true;
    //                Timer.Start();
    //                //ReceiveThread = new Thread(UartRecive);
    //                //ReceiveThread.Start();
    //                break;
    //            default:
    //                throw new Exception("不支持的通信方式");
    //        }
    //        return 0;
    //    }
    //    public override void Connect()
    //    {
    //        if (ConnectState)
    //        {
    //            //设备已经连接
    //            return;
    //        }
    //        string SelectedCommunication = "";
    //        foreach (var temp in Config.CommunicationList)
    //        {
    //            if (temp.Selected)
    //            {
    //                SelectedCommunication = temp.Name;
    //            }
    //        }


    //        switch (SelectedCommunication.ToUpper())
    //        {
    //            case "TCP":
    //                Connect(new IPEndPoint(IPAddress.Parse(Config.DestIP), int.Parse(Config.DestPort)), 1000);
    //                Send_Func = SendData;
    //                StopThreadFlag = false;
    //                StartReceive();
    //                break;
    //            case "UDP":
    //                ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    //                //解决远程主机强迫关闭了一个现有的连接
    //                uint IOC_IN = 0x80000000;
    //                uint IOC_VENDOR = 0x18000000;
    //                uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
    //                ClientSocket.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);
    //                ClientSocket.Bind(new IPEndPoint(IPAddress.Parse(Config.LocalIP), int.Parse(Config.LocalPort)));//绑定端口号和IP
    //                EndPoint = new IPEndPoint(IPAddress.Parse(Config.DestIP), int.Parse(Config.DestPort));
    //                Send_Func = SendData;
    //                StopThreadFlag = false;
    //                StartReceive();
    //                break;
    //            case "UART":
    //                SerialPort = new SerialPort();
    //                SerialPort.PortName = Config.PortName;
    //                SerialPort.BaudRate = int.Parse(Config.BandRate);
    //                SerialPort.Open();
    //                Send_Func = SendData;
    //                StopThreadFlag = false;
    //                StartReceive();
    //                break;
    //            default:
    //                throw new Exception("不支持的通信方式");
    //        }
    //        ConnectState = true;
    //    }

    //    public int TerminateReceive()
    //    {
    //        string SelectedCommunication = "";
    //        foreach (var temp in Config.CommunicationList)
    //        {
    //            if (temp.Selected)
    //            {
    //                SelectedCommunication = temp.Name;
    //            }
    //        }
    //        try
    //        {
    //            switch (SelectedCommunication.ToUpper())
    //            {
    //                case "TCP":
    //                    StopThreadFlag = true;
    //                    while (ReceiveThread?.ThreadState != ThreadState.Stopped)
    //                    {

    //                    }
    //                    ReceiveThread = null;
    //                    break;
    //                case "UDP":
    //                    StopThreadFlag = true;
    //                    while (ReceiveThread?.ThreadState != ThreadState.Stopped)
    //                    {

    //                    }
    //                    ReceiveThread = null;
    //                    Timer!.Enabled = false;
    //                    Timer!.Close();
    //                    Timer!.Dispose();
    //                    break;
    //                case "UART":
    //                    if (SerialPort != null)
    //                    {
    //                        SerialPort.DataReceived -= SerialPort_DataReceived; //用接收事件接收数据,也可开启线程接收
    //                    }
    //                    Timer!.Enabled = false;
    //                    Timer!.Close();
    //                    Timer!.Dispose();
    //                    //StopThreadFlag= true;
    //                    //while(ReceiveThread.ThreadState!= ThreadState.Stopped)
    //                    //{

    //                    //}
    //                    //ReceiveThread = null;
    //                    break;
    //                default:
    //                    throw new Exception("不支持的通信方式");
    //            }
    //        }
    //        catch (Exception)
    //        {

    //            throw;
    //        }
    //        return 0;
    //    }
    //    public override void DisConnect()
    //    {
    //        if (!ConnectState)
    //        {
    //            //已经断开连接
    //            return;
    //        }
    //        string SelectedCommunication = "";
    //        foreach (var temp in Config.CommunicationList)
    //        {
    //            if (temp.Selected)
    //            {
    //                SelectedCommunication = temp.Name;
    //            }
    //        }
    //        switch (SelectedCommunication.ToUpper())
    //        {
    //            case "TCP":
    //                ClientSocket?.Disconnect(false);
    //                ClientSocket?.Dispose();
    //                ClientSocket = null;
    //                TerminateReceive();
    //                break;
    //            case "UDP":
    //                ClientSocket?.Close();
    //                ClientSocket?.Dispose();
    //                ClientSocket = null;
    //                TerminateReceive();
    //                break;
    //            case "UART":
    //                TerminateReceive();
    //                SerialPort?.Close();
    //                SerialPort?.Dispose();
    //                SerialPort = null;
    //                break;
    //            default:
    //                throw new Exception("不支持的通信方式");
    //        }
    //        ConnectState = false;
    //    }


    //    public void BuildCommand(ref byte[] Command, int Cmd_M, int Cmd_A, List<DataSegment>? Data = null)
    //    {
    //        int Length = 0;
    //        byte Sum = 0;
    //        byte[] cmd = new byte[1];
    //        if (Data == null)
    //        {
    //            Length = 6;
    //        }
    //        else
    //        {
    //            foreach (var temp in Data)
    //            {
    //                switch (temp.Type)
    //                {
    //                    case "byte":
    //                        Length += 1;
    //                        cmd = cmd.Concat(new byte[1] { byte.Parse(temp.Value) }).ToArray();
    //                        break;
    //                    case "short":
    //                        Length += 2;
    //                        cmd = cmd.Concat(BitConverter.GetBytes(short.Parse(temp.Value))).ToArray();
    //                        break;
    //                    case "int":
    //                        Length += 4;
    //                        cmd = cmd.Concat(BitConverter.GetBytes(int.Parse(temp.Value))).ToArray();
    //                        break;
    //                    case "float":
    //                        Length += 4;
    //                        cmd = cmd.Concat(BitConverter.GetBytes(float.Parse(temp.Value))).ToArray();
    //                        break;
    //                    case "double":
    //                        Length += 8;
    //                        cmd = cmd.Concat(BitConverter.GetBytes(double.Parse(temp.Value))).ToArray();
    //                        break;
    //                    case "string":
    //                        Length += System.Text.Encoding.Default.GetBytes(temp.Value).Length;
    //                        cmd = cmd.Concat(System.Text.Encoding.Default.GetBytes(temp.Value)).ToArray();
    //                        break;
    //                    default:
    //                        throw new Exception("不支持的数据类型!");
    //                }
    //            }
    //            Length += 6;
    //        }
    //        Array.Resize(ref Command, Length);
    //        Array.Clear(Command);
    //        Command[0] = (byte)'c';
    //        Command[1] = (byte)'p';
    //        Command[2] = (byte)Length;
    //        Command[3] = (byte)Cmd_M;
    //        Command[4] = (byte)Cmd_A;
    //        if (Data != null)
    //        {
    //            for (int i = 0; i < Length - 6; i++)
    //            {
    //                Command[i + 5] = cmd[1 + i];
    //            }
    //        }
    //        for (int i = 0; i < Length - 1; i++)
    //        {
    //            Sum += Command[i];
    //        }
    //        Command[Length - 1] = (byte)Sum;
    //    }

    //    public override int Enable(int AxisID)
    //    {
    //        byte[] Command = new byte[1];
    //        var dataSegments = new List<DataSegment>();
    //        dataSegments.Add(new DataSegment() { Value = AxisID.ToString(), Type = "byte" });
    //        BuildCommand(ref Command, 0, 1, dataSegments);
    //        SendData(Command);
    //        return 0;
    //    }
    //    public override int Disable(int AxisID)
    //    {
    //        byte[] Command = new byte[1];
    //        var dataSegments = new List<DataSegment>();
    //        dataSegments.Add(new DataSegment() { Value = AxisID.ToString(), Type = "byte" });
    //        BuildCommand(ref Command, 0, 0, dataSegments);
    //        SendData(Command);
    //        return 0;

    //    }
    //    public override int Run(int AxisID, double Position, double Speed, double Acc, double Dcc, bool AbsoluteMovement = true)
    //    {
    //        byte[] Command = new byte[1];
    //        List<DataSegment> dataSegments = new List<DataSegment>();
    //        dataSegments.Add(new DataSegment() { Value = AxisID.ToString(), Type = "byte" });
    //        dataSegments.Add(new DataSegment() { Value = Position.ToString(), Type = "float" });
    //        dataSegments.Add(new DataSegment() { Value = Speed.ToString(), Type = "float" });
    //        if (AbsoluteMovement)
    //        {
    //            dataSegments.Add(new DataSegment() { Value = "1", Type = "byte" });
    //        }
    //        else
    //        {
    //            dataSegments.Add(new DataSegment() { Value = "0", Type = "byte" });
    //        }

    //        BuildCommand(ref Command, 1, 1, dataSegments);
    //        SendData(Command);
    //        return 0;
    //    }

    //    public override int Stop(int AxisID)
    //    {
    //        byte[] Command = new byte[1];
    //        var dataSegments = new List<DataSegment>();
    //        dataSegments.Add(new DataSegment() { Value = AxisID.ToString(), Type = "byte" });
    //        BuildCommand(ref Command, 1, 0, dataSegments);
    //        SendData(Command);
    //        return 0;
    //    }

    //    public override void ReSet()
    //    {
    //        throw new NotImplementedException();
    //    }

    //    public override bool ReachedState(int AxisID)
    //    {
    //        throw new NotImplementedException();
    //    }

    //    public override int TriggerOpen(int AxisID, double StartPosition, double EndPosition, double Interval, int PuslseWidth_us)
    //    {
    //        byte[] Command = new byte[1];
    //        var dataSegments = new List<DataSegment>();
    //        dataSegments.Add(new DataSegment() { Value = AxisID.ToString(), Type = "byte" });
    //        dataSegments.Add(new DataSegment() { Value = StartPosition.ToString(), Type = "float" });
    //        BuildCommand(ref Command, 2, 2, dataSegments);
    //        SendData(Command);
    //        Thread.Sleep(10);
    //        dataSegments = new List<DataSegment>();
    //        dataSegments.Add(new DataSegment() { Value = AxisID.ToString(), Type = "byte" });
    //        dataSegments.Add(new DataSegment() { Value = EndPosition.ToString(), Type = "float" });
    //        BuildCommand(ref Command, 2, 3, dataSegments);
    //        SendData(Command);
    //        Thread.Sleep(10);
    //        dataSegments = new List<DataSegment>();
    //        dataSegments.Add(new DataSegment() { Value = AxisID.ToString(), Type = "byte" });
    //        dataSegments.Add(new DataSegment() { Value = Interval.ToString(), Type = "float" });
    //        BuildCommand(ref Command, 2, 4, dataSegments);
    //        SendData(Command);
    //        Thread.Sleep(10);
    //        dataSegments = new List<DataSegment>();
    //        dataSegments.Add(new DataSegment() { Value = AxisID.ToString(), Type = "byte" });
    //        dataSegments.Add(new DataSegment() { Value = PuslseWidth_us.ToString(), Type = "int" });
    //        BuildCommand(ref Command, 2, 5, dataSegments);
    //        SendData(Command);
    //        Thread.Sleep(10);
    //        dataSegments = new List<DataSegment>();
    //        dataSegments.Add(new DataSegment() { Value = AxisID.ToString(), Type = "byte" });
    //        BuildCommand(ref Command, 2, 1, dataSegments);
    //        SendData(Command);
    //        return 0;
    //    }

    //    public override int TriggerClose(int AxisID)
    //    {
    //        byte[] Command = new byte[1];
    //        var dataSegments = new List<DataSegment>();
    //        dataSegments.Add(new DataSegment() { Value = AxisID.ToString(), Type = "byte" });
    //        BuildCommand(ref Command, 2, 0, dataSegments);
    //        SendData(Command);
    //        return 0;
    //    }

    //    public override int TriggerOne(int AxisID)
    //    {
    //        byte[] Command = new byte[1];
    //        var dataSegments = new List<DataSegment>();
    //        dataSegments.Add(new DataSegment() { Value = AxisID.ToString(), Type = "byte" });
    //        BuildCommand(ref Command, 2, 6, dataSegments);
    //        SendData(Command);
    //        return 0;
    //    }
    //}
}
